/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package central.server.gui;

import central.server.CentralOperator;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JTabbedPane;
import javax.swing.Timer;

/**
 *
 * @author mire
 */
public class CentralServerOperatorsTabs {

    private ConcurrentHashMap<String, CentralOperator> operators;
    private JTabbedPane tabbedPane;
    private HashSet<CentralOperator> currentTabs;
    private Timer t;
    private Dimension dimensions;

    public CentralServerOperatorsTabs(ConcurrentHashMap<String, CentralOperator> operators, JTabbedPane tabbedPane, Dimension dimensions) {
        this.tabbedPane = tabbedPane;
        this.operators = operators;
        this.dimensions = dimensions;
        this.currentTabs = null;
        setTimer();
    }

    private void fillTabs() {

        if (operators.isEmpty()) {
            return;
        }

        HashSet<CentralOperator> entrySet = new HashSet<CentralOperator>(operators.values());

        if (entrySet.equals(currentTabs)) {
            return;
        }

        HashSet<CentralOperator> toBeAdded = new HashSet<CentralOperator>(entrySet);
        HashSet<CentralOperator> toBeDeleted;
        if (currentTabs == null) {
            toBeDeleted = new HashSet<CentralOperator>();
        } else {
            toBeDeleted = new HashSet<CentralOperator>(currentTabs);

            toBeAdded.removeAll(currentTabs);
            toBeDeleted.removeAll(entrySet);
        }

        if (!toBeDeleted.isEmpty()) {
            for (int i = 0; i < tabbedPane.getTabCount(); i++) {
                CentralOperator o = ((CentralOperatorInfo) tabbedPane.getTabComponentAt(i)).getOperator();
                if (toBeDeleted.contains(o)) {
                    tabbedPane.removeTabAt(i);
                }
            }
        }

        if (!toBeAdded.isEmpty()) {
            for (Iterator<CentralOperator> it = toBeAdded.iterator(); it.hasNext();) {
                CentralOperator operator = it.next();
                CentralOperatorInfo oInfo = new CentralOperatorInfo(operator,dimensions);
                tabbedPane.addTab(operator.getName(), oInfo);
            }
        }

        currentTabs = entrySet;
    }

    private void setTimer() {
        t = new javax.swing.Timer(1000, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                fillTabs();
                tabbedPane.repaint();
            }
        });
    }

    public void start() {
        t.start();
    }
}
